package com.example.gw_back_end.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gw_back_end.domain.PageResult;
import com.example.gw_back_end.domain.entities.Warehouse;
import com.example.gw_back_end.mapper.WarehouseMapper;
import com.example.gw_back_end.service.WarehouseService;
import com.example.gw_back_end.utils.ThreadLocalUtil;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {
    private final WarehouseMapper warehouseMapper;

    public WarehouseServiceImpl(WarehouseMapper warehouseMapper) {
        this.warehouseMapper = warehouseMapper;
    }

    @Override
    public boolean addWarehouse(Warehouse warehouse) {
        return warehouseMapper.insert(warehouse) > 0;
    }

    @Override
    public boolean deleteWarehouse(Integer id) {
        return warehouseMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateWarehouse(Warehouse warehouse) {
        return warehouseMapper.updateById(warehouse) > 0;
    }

    @Override
    public Warehouse getWarehouseById(Integer id) {
        return warehouseMapper.selectById(id);
    }

    @Override
    public PageResult<Warehouse> getAllWarehouses() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Warehouse::getUserId, id);
        queryWrapper.orderByAsc(Warehouse::getId);
        List<Warehouse> temPage = warehouseMapper.selectList(queryWrapper);
        Page<Warehouse> page = new Page<>();
        page.setRecords(temPage);
        page.setTotal(warehouseMapper.selectCount(queryWrapper));
        page.setCurrent(1);
        page.setSize(temPage.size());
        page.setPages(1);
        return PageResult.setPageResult(page);
    }
}
